package com.auto.learning.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.adapter.HomePageListViewAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.BookNumChangeEvent;
import com.auto.learning.event.CollectEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

/***
 * 选书页面
 * @author jianjun
 *
 */
public class TopBookListFragment extends Fragment {

	
	private PullToRefreshListView choose_listview;
	private HomePageListViewAdapter adapter;
	private ArrayList<BookBean> bookList = new ArrayList<BookBean>();

	private View lvProductFooter;
	private TextView lvProductFooterMore;
	private ProgressBar lvProductFooterProgress;
	private TextView lvBtn_more;
	private LinearLayout lvLinear_more;

	private int pageIndex = 0;
	private int bookType ;
	

	private int type = 1; //1，周榜，2，月榜


	private Handle handle = new Handle(getActivity()) {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				String bottom = "";
				ResponeResult result = (ResponeResult) msg.obj;
				ArrayList<BookBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<BookBean>>() {}.getType());
				/**
				 * 把书缓存到本地
				 */
				Cache.cacheChoosePageList2Local(resultList);
				if (pageIndex == 0) {
					bookList.clear();
					bookList.addAll(resultList);
				} else {
					bookList.addAll(resultList);
				}
				if (resultList.size() >= 10) {
					pageIndex++;
					lvBtn_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
				} else {
					bottom = getResources().getString(
							R.string.text_hompage_data);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
					lvProductFooterProgress.setVisibility(View.GONE);
					lvBtn_more.setVisibility(View.GONE);
				}

				if (choose_listview != null) {
					choose_listview.onRefreshComplete();
					choose_listview.setTag(0);
				}
				if (bookList != null && bookList.size() > 0) {
					adapter.notifyDataSetChanged();
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				try {
					if (choose_listview != null) {
						choose_listview.onRefreshComplete();
						choose_listview.setTag(0);
					}
					if (msg.obj != null) {
						CommonMethod.makeNotice(getActivity(), msg.obj.toString() + "");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case 2:
				if (bookList != null) {
					for (int i = 0; i < bookList.size(); i++) {
						if (bookList.get(i).getBookId() == msg.arg1) {
							bookList.get(i).setIsRead(2);
							break;
						}
					}	
				}
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
				break;
			}
		};
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.new_booklist_activity, null);
		initView(view);
		registerEvent();
		return view;
	}
	
	@Subscribe
	public void onEventCollectSuccess(CollectEvent event) {
		if (bookList != null && bookList.size() > 0) {
			for (int i = 0; i < bookList.size(); i++) {
				if (event.getBookId() == bookList.get(i).getBookId()) {
					bookList.get(i).setIsFavor(event.isCollect() ? 2 : 1);
				}
			}
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}
	

	@Subscribe
	public void readBookNumChange(BookNumChangeEvent event){
		handle.obtainMessage(2, event.getBookId(), 0).sendToTarget();
	}
	

	public void registerEvent() {
		EventBus.getEventBus("readbook_num_change" , ThreadEnforcer.MAIN).register(this);
	}

	public void unregisterEvent() {
		EventBus.getEventBus("readbook_num_change" , ThreadEnforcer.MAIN).register(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterEvent();
	}

	private void initView(View view) {
		lvProductFooter = getActivity().getLayoutInflater().inflate(R.layout.listview_footer,null);
		lvProductFooterMore = (TextView) lvProductFooter.findViewById(R.id.listview_foot_more);
		lvProductFooterProgress = (ProgressBar) lvProductFooter.findViewById(R.id.listview_foot_progress);
		lvBtn_more = (TextView) lvProductFooter.findViewById(R.id.btn_more);
		lvLinear_more = (LinearLayout) lvProductFooter.findViewById(R.id.linear_more);

		choose_listview = (PullToRefreshListView) view.findViewById(R.id.choose_listview);
		adapter = new HomePageListViewAdapter(getActivity(), bookList);
		choose_listview.setAdapter(adapter);
		choose_listview.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				pageIndex = 0;
				getData();
			}
		});
		choose_listview.setTag(0);
		choose_listview.addFooterView(lvProductFooter);
		lvBtn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getData();
			}
		});
		choose_listview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				choose_listview.onScrollStateChanged(view, scrollState);
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvProductFooter) == view.getLastVisiblePosition()
							&& !lvProductFooterMore.getText().toString().equals(getResources().getString(R.string.text_hompage_data))) {
						scrollEnd = true;
					}
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = Integer.parseInt((choose_listview.getTag().toString()));
				if (scrollEnd && lvDataState == 0) {
					choose_listview.setTag(1);
					lvProductFooterMore.setText("加载中");
					lvProductFooterProgress.setVisibility(View.VISIBLE);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvBtn_more.setVisibility(View.GONE);
					int page = choose_listview.getCount() - 2; // 减去ListView的头和尾的
					getData();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				choose_listview.onScroll(view, firstVisibleItem,visibleItemCount, totalItemCount);
			}
		});
		choose_listview.clickRefresh();
	}

	public void notifyUI() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}

	private void getData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(),HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String.valueOf(pageIndex)));
		params.add(new BasicNameValuePair("typeId", String.valueOf(bookType)));
		HttpRequestHelper.executeHttpData(getActivity(),type == 1 ? HttpRequestHelper.SEARCH_HOT : HttpRequestHelper.SEARCH, params, handle,HttpRequestHelper.GETDATA_SUCCESS,HttpRequestHelper.GETDATA_FAIL);
	}

	public void refreshUI() {
		if (choose_listview != null) {
			pageIndex = 0;
			choose_listview.clickRefresh();
		}
	}
	
	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}
	
	public int getBookType() {
		return bookType;
	}

	public void setBookType(int bookType) {
		this.bookType = bookType;
	}
}
